package com.bootdo.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.SnowflakeIdWorker;
import com.bootdo.haojiangboutils.MapBuild;
import com.bootdo.hotel.domain.HotelMember;
import com.bootdo.hotel.domain.HotelRoom;
import com.bootdo.hotel.service.HotelMemberService;
import com.bootdo.hotel.service.HotelRoomService;
import com.bootdo.mall.domain.GoodSpecs;
import com.bootdo.mall.domain.MallGood;
import com.bootdo.mall.domain.MallOrderLog;
import com.bootdo.mall.service.GoodSpecsService;
import com.bootdo.mall.service.MallGoodService;
import com.bootdo.mall.service.MallOrderLogService;
import com.bootdo.mall_part.domain.StatusNumberVo;
import com.bootdo.member.domain.ShequIntegralRecord;
import com.bootdo.member.domain.ShequMember;
import com.bootdo.member.service.ShequIntegralRecordService;
import com.bootdo.member.service.ShequMemberService;
import com.bootdo.redis.RedisUtil;
import com.bootdo.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import com.bootdo.mall.dao.MallOrderDao;
import com.bootdo.mall.domain.MallOrder;
import com.bootdo.mall.service.MallOrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;


@Service
public class MallOrderServiceImpl implements MallOrderService {
	@Autowired
	private MallOrderDao mallOrderDao;

	@Autowired
	private HotelRoomService hotelRoomService;

	@Autowired
	private HotelMemberService hotelMemberService;

	@Autowired
	private MallGoodService mallGoodService;

	@Autowired
	private MallOrderLogService mallOrderLogService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private GoodSpecsService goodSpecsService;
	@Autowired
	private ShequMemberService shequMemberService;
	@Autowired
	private ShequIntegralRecordService shequIntegralRecordService;


	@Override
	public MallOrder get(Long id){
		return mallOrderDao.get(id);
	}

	@Override
	public MallOrder getByOrderId(String orderId) {
		return mallOrderDao.getByOrderId(orderId);
	}

	@Override
	public List<MallOrder> list(Map<String, Object> map){
		return mallOrderDao.list(map);
	}

	@Override
	public List<MallOrder> getSum(Map<String, Object> map) {
		return mallOrderDao.getSum(map);
	}

	@Override
	public List<Integer> getSumCount(Map<String, Object> map) {
		return mallOrderDao.getSumCount(map);
	}

	@Override
	public Integer updatePayStatus(Long id, Integer newStatus, Integer oldStatus, Double payMoney) {
		return mallOrderDao.updatePayStatus(id, newStatus, oldStatus, payMoney);
	}

	@Override
	public Integer updatePayStatusByOrderNo(String orderNo, Integer newStatus, String payOrderNo, Integer oldStatus) {
		return mallOrderDao.updatePayStatusByOrderNo(orderNo,newStatus,payOrderNo,oldStatus);
	}

	@Override
	public Integer updatePayStatusByOrderId(String orderId, Integer newStatus,Long overOrderTime, String wuliuName, String wuliuOrderNo, Integer oldStatus) {
		return mallOrderDao.updatePayStatusByOrderId(orderId, newStatus,overOrderTime, wuliuName, wuliuOrderNo, oldStatus);
	}

	@Override
	public Integer updateFahuoTimeByOrderId(String orderId, Date fahuoTime) {
		return mallOrderDao.updateFahuoTimeByOrderId(orderId, fahuoTime);
	}

	@Override
	public Integer delPriceByOrderId(String orderId, Double price, Integer num) {
		return mallOrderDao.delPriceByOrderId(orderId, price, num);
	}


	@Override
	public int count(Map<String, Object> map){
		return mallOrderDao.count(map);
	}

	@Override
	public Map getTotalOrderPar(Map<String, Object> map) {
		return mallOrderDao.getTotalOrderPar(map);
	}

	@Override
	public List<StatusNumberVo> statusCount(Map<String, Object> map) {
		return mallOrderDao.statusCount(map);
	}

	@Override
	public int save(MallOrder mallOrder){
	
		if(mallOrder.getId() != null) {
			return mallOrderDao.update(mallOrder);
		}else {
			return mallOrderDao.save(mallOrder);
		}		
	
		
	}
	
	@Override
	public int update(MallOrder mallOrder){
		return mallOrderDao.update(mallOrder);
	}
	
	@Override
	public int remove(String orderNo){
		return mallOrderDao.remove(orderNo);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return mallOrderDao.batchRemove(ids);
	}

	@Override
	public List<Map> tongJi(HashMap<String, Object> map) {
		return mallOrderDao.tongJi(map);
	}

	/**
	 * 此方法已废弃
	 * @param memberId
	 * @param roomId
	 * @param map
	 * @param request
	 * @return
	 */
	@Override
	@Transactional

	public R createOrderFunction(Long memberId, Long roomId, Map map, HttpServletRequest request) {

		return R.ok();
	}

	@Override

	public R quxiaoOrderFunction(Long id,Integer newStatus,Integer oldStatus) {
		return R.ok();
	}

	/**
	 * 在线支付
	 * @param orders
	 * @return
	 */
	@Override
	@Transactional
	public synchronized boolean saveOrderByWx(List<MallOrder> orders) {
		for(MallOrder order : orders){
			for(MallOrderLog log : order.getMallOrderLogs()){
				int count = goodSpecsService.delStock(log.getTotalNum(), log.getSpecsId());
				if(count <= 0){
					throw  new RuntimeException(log.getGoodName()+"库存不足");
				}
				mallOrderLogService.save(log);
			}
			mallOrderDao.save(order);
		}
		return true;
	}

	/**
	 * 积分购买
	 * @param orders
	 * @return
	 */
	@Transactional
	@Override
	public synchronized boolean  saveOrderByJiFen(List<MallOrder> orders) {
		AtomicReference<Double> payMoney = new AtomicReference<>(0d);
		if(orders.size() <= 0){
			throw  new RuntimeException("订单集合小于0");
		}
		for(MallOrder order : orders){
			payMoney.updateAndGet(v -> new Double((double) (v + order.getPayMoney())));
			for(MallOrderLog log : order.getMallOrderLogs()){
				int count = goodSpecsService.delStock(log.getTotalNum(), log.getSpecsId());
				if(count <= 0){
					throw  new RuntimeException(log.getGoodName()+"库存不足");
				}
				mallOrderLogService.save(log);
			}
			order.setType(2);
			order.setPayStatus(1);
			mallOrderDao.save(order);
		}
		MallOrder order = orders.get(0);


		//用户积分相关逻辑
		try {
			if(order.getType().intValue() == 2){
				ShequMember shequMember = shequMemberService.getByMobile(order.getMemberMobile());
				if(null == shequMember){
					throw  new RuntimeException("会员不存在");
				}
				int r = shequMemberService.updateIntegerMinus(payMoney.get(),order.getMemberMobile());
				if(r <= 0){
					throw  new RuntimeException("用户积分不足");
				}
				ShequIntegralRecord shequIntegralRecord = new ShequIntegralRecord();
				shequIntegralRecord.setCommunityId(shequMember.getCommunityId());
				shequIntegralRecord.setCommunityName(shequMember.getCommunityName());
				shequIntegralRecord.setIntegrals(payMoney.get());
				shequIntegralRecord.setMemberMobile(shequMember.getMobile());
				shequIntegralRecord.setMemberId(shequMember.getId());
				shequIntegralRecord.setMemberName(shequMember.getRealName());
				shequIntegralRecord.setState(1);
				shequIntegralRecord.setRemarks("购买商品消费："+payMoney.get()+"积分，<br/>流水号："+order.getOrderNo());
				shequIntegralRecordService.save(shequIntegralRecord);
			}
		}catch (Exception e){
			e.printStackTrace();
			throw  new  RuntimeException(e.getMessage());
		}

		return true;
	}

	/**
	 * 订单支付成功修改状态方法
	 * @param orderNo
	 * @param wxPayOkOrderNo
	 * @return
	 */
	@Override
	@Transactional
	public boolean orderPayOk(String orderNo, String wxPayOkOrderNo) {
		List<MallOrder> list = list(MapBuild.getInstand().setKV("orderNo",orderNo));
		int r = updatePayStatusByOrderNo(orderNo, 1, wxPayOkOrderNo, 0);
		if(r <= 0){
			throw  new RuntimeException("订单状态修改失败");
		}
		for(MallOrder order : list){
			if(order.getDelFlag().intValue() == 1){
				List<MallOrderLog> logs  = mallOrderLogService.list(MapBuild.getInstand().setKV("orderId", order.getOrderId()));
				for(MallOrderLog log : logs){
					goodSpecsService.delStock(log.getTotalNum(), log.getSpecsId());
				}
			}
		}
		return true;
	}

	/**
	 * 清除过期订单的事务方法
	 * @param orderNo
	 * @return
	 */
	@Override
	@Transactional
	public String delOrder(String orderNo) {
	   List<MallOrder> mallOrders = list(MapBuild.getInstand().setKV("orderNo", orderNo).setKV("status", 0));
	   if(mallOrders.size() <= 0){
	   		return "OK";
	   }
	   int r =  remove(orderNo);
	   if(r != mallOrders.size()){
	   		throw new RuntimeException("状态修改失败");
	   }
	   for(MallOrder mallOrder : mallOrders){
		   List<MallOrderLog> logs  = mallOrderLogService.list(MapBuild.getInstand().setKV("orderId", mallOrder.getOrderId()));
		   for(MallOrderLog log : logs){
			   int row =  goodSpecsService.addStock(log.getTotalNum(), log.getSpecsId());
			   if(row == 0){
			   		throw new RuntimeException("库存增加失败");
			   }
		   }
	   }
	   return "ok";
	}

	@Override
    @Transactional
	public String tuiHuoByOrderLogId(Long orderLogId,Integer num) {
		MallOrderLog log =  mallOrderLogService.get(orderLogId);
		if(null == log){
			return "订单不存在";
		}

		if(num <= 0){
			return "必须大于0";
		}

		//修改订单日志状态 及价格
		int row = mallOrderLogService.updateIsTuiKuanById(orderLogId,  num);
		if(row <= 0){
			throw new RuntimeException("详情状态修改失败");
		}

		//增加对应库存
		row =  goodSpecsService.addStock(num, log.getSpecsId());
		if(row <= 0){
			throw new RuntimeException("库存修改失败");
		}

		//主订单修改对应价格
		row = delPriceByOrderId(log.getOrderId(), num * log.getPrice() , num);
		if(row <= 0){
			throw new RuntimeException("订单款项扣除失败");
		}

		/*row = updatePayStatusByOrderId(log.getOrderId(), null,null,null,null,null);
		if(row <= 0){
			throw new RuntimeException("订单状态修改失败");
		}*/

		return "退货成功";
	}

	@Override
	@Transactional
	public String tuiHuoByOrderId(String orderId) {
		MallOrder  order =  mallOrderDao.getByOrderId(orderId);
		if(null == order){
			return "订单不存在";
		}
		List<MallOrderLog> logList =
				mallOrderLogService.list(MapBuild.getInstand().setKV("orderId", orderId));
		int row = 0;
		if(logList.size() > 0){
			for(MallOrderLog log : logList){
				//修改订单日志状态 及价格
				row = mallOrderLogService.updateIsTuiKuanById(log.getId(),  log.getTotalNum());
				if(row <= 0){
					throw new RuntimeException("详情状态修改失败");
				}

				//增加对应库存
				row =  goodSpecsService.addStock(log.getTotalNum(), log.getSpecsId());
				if(row <= 0){
					throw new RuntimeException("库存修改失败");
				}

				//主订单修改对应价格
				row = delPriceByOrderId(log.getOrderId(), log.getTotalPrice() , log.getTotalNum());
				if(row <= 0){
					throw new RuntimeException("订单款项扣除失败");
				}
			}

			row = updatePayStatusByOrderId(orderId, 5,null,null,null,null);
			if(row <= 0){
				throw new RuntimeException("订单状态修改失败");
			}
			try {
				if(order.getType().intValue() == 2){
					ShequMember shequMember = shequMemberService.getByMobile(order.getMemberMobile());
					if(null == shequMember){
						throw  new RuntimeException("会员不存在");
					}
					int r =  shequMemberService.updateIntegerAdd(order.getPayMoney(),order.getMemberMobile());
					if(r <= 0){
						throw  new RuntimeException("用户积分不足");
					}
					ShequIntegralRecord shequIntegralRecord = new ShequIntegralRecord();
					shequIntegralRecord.setCommunityId(shequMember.getCommunityId());
					shequIntegralRecord.setCommunityName(shequMember.getCommunityName());
					shequIntegralRecord.setIntegrals(order.getPayMoney());
					shequIntegralRecord.setMemberMobile(shequMember.getMobile());
					shequIntegralRecord.setMemberId(shequMember.getId());
					shequIntegralRecord.setMemberName(shequMember.getRealName());
					shequIntegralRecord.setState(1);
					shequIntegralRecord.setCountType(1);
					shequIntegralRecord.setRemarks("取消订单返回积分："+order.getPayMoney()+"<br/>订单号："+order.getOrderId());
					shequIntegralRecordService.save(shequIntegralRecord);
				}
			}catch (Exception e){
				e.printStackTrace();
				throw  new  RuntimeException(e.getMessage());
			}

		}else{
			return "退单失败";
		}
		return "退单成功";
	}

	/**
	 * 订单确认收货  赠送积分
	 * @param list
	 * @return
	 */
	@Override
	@Transactional
	public String overOrderByOrderId(List<MallOrder> list) {
		if(list.size() > 0){
			double totalJifen = 0d;
			for(MallOrder order : list){
				int row =   updatePayStatusByOrderId(order.getOrderId(), 3,
						System.currentTimeMillis(),
						null, null, null);
				if(row > 0){
					List<MallOrderLog> logs  = mallOrderLogService.list(MapBuild.getInstand().setKV("orderId", order.getOrderId()));
					for(MallOrderLog log : logs){
						/*MallGood mallGood = 	mallGoodService.get(log.getGoodId());*/
						GoodSpecs goodSpecs =  goodSpecsService.get(log.getSpecsId());
						log.setReturnJifen(goodSpecs.getReturnIntegral() * log.getTotalNum());
						mallOrderLogService.save(log);
						totalJifen += (goodSpecs.getReturnIntegral() * log.getTotalNum());
					}
				}else{
					throw  new RuntimeException("订单状态修改失败");
				}

				ShequMember shequMember = shequMemberService.getByMobile(order.getMemberMobile());
				if(null == shequMember){
					throw  new RuntimeException("会员不存在");
				}
				if(totalJifen <= 0){
					return  "OK";
				}
				int r =  shequMemberService.updateIntegerAdd(totalJifen,order.getMemberMobile());
				if(r <= 0){
					throw  new RuntimeException("用户积分不足");
				}
				ShequIntegralRecord shequIntegralRecord = new ShequIntegralRecord();
				shequIntegralRecord.setCommunityId(shequMember.getCommunityId());
				shequIntegralRecord.setCommunityName(shequMember.getCommunityName());
				shequIntegralRecord.setIntegrals(totalJifen);
				shequIntegralRecord.setMemberMobile(shequMember.getMobile());
				shequIntegralRecord.setMemberId(shequMember.getId());
				shequIntegralRecord.setMemberName(shequMember.getRealName());
				shequIntegralRecord.setState(1);
				shequIntegralRecord.setCountType(1);
				shequIntegralRecord.setRemarks("购买商品赠送积分："+totalJifen+"<br/>订单号："+order.getOrderId());
				shequIntegralRecordService.save(shequIntegralRecord);
		}


		}
		return "OK";
	}
}
